#! /usr/bin/env python
#coding=utf-8
import sys
import os.path

sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "/"))
from cxxfilt import demangle

# https://subscription.packtpub.com/book/networking-and-servers/9781782167105/2/ch02lvl1sec15/elf-symbols

class Symbol(dict):
	def __init__(self, name, library, bits):
		self["name"] = name
		self["library"] = library
		self["bits"] = bits
		#try:
		#	self["demangle"] = self.demangle()
		#except:
		#	self["demangle"] = self["name"]

	def __str__(self):
		ret = [self.name]
		if self.bits:
			ret.append(self.bits)
		return '@'.join(ret)

	def get_id(self, idx):
		if "id" in self["library"]:
			return (self["library"]["id"] << 20) + idx
		return idx

	def demangle(self):
		#output = command("c++filt " + self["name"])
		try:
			return demangle(self["name"])
		except:
			return self["name"]

class ProvidedSymbol(Symbol):
	def __init__(self, name, library, bits, addr, section, name_type):
		super(ProvidedSymbol, self).__init__(name, library, bits)
		self["addr"] = addr
		self["section"] = section
		self["name_type"] = name_type

if __name__ == '__main__':
	def test_demangle(name):
		try:
			res = cxxfilt.demangle(name)
		except:
			res = name
		return res

	print(test_demangle("_ZTVNSt3__h14basic_ifstreamIcNS_11char_traitsIcEEEE"))
